package com.heaven.controller;

import java.sql.SQLException;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.heaven.model.Account;
import com.heaven.service.AccountService;

@Controller
public class AccountController {
	private AccountService as = new AccountService();
	// 입금 실행
	// account1 : 계좌 정보
	// money : 입금액
	@RequestMapping(value="/account/deposit", method = RequestMethod.POST)
	public String deposit(Model model, int accountNo, int money) throws ClassNotFoundException, SQLException {
		Account account = as.deposit(accountNo, money);
		
		model.addAttribute("account", account);
		
		return "redirect:/account/list";
	}	

	// 출금
	// account1 : 계좌 정보
	// money : 출금액
	public void withdraw(Account account1, int money) throws Exception {
		int balance = account1.getBalance();
		
		if(balance >= money) {
			account1.setBalance(balance - money);
		} else {
			throw new Exception("잔액이 부족합니다.");
		}
	}

	// 이체
	// account1 은 출금 계좌
	// account2 은 입금 계좌
	// money 이체액
	public void transfer(Account account1, Account account2, int money) throws Exception {
		//int balance1 = account1.getBalance();
		//int balance2 = account2.getBalance();
		
		//account1.setBalance(balance1 - money);
		//account2.setBalance(balance2 + money);

		//withdraw(account1, money);
		//deposit(account2, money);
	}

	@RequestMapping(value="/account/list")
	public String list(Model model) throws ClassNotFoundException, SQLException {
		List<Account> accounts = as.list();
		
		model.addAttribute("accounts", accounts);
		
		return "account/list";
	}
	
	@RequestMapping(value="/account/detail") 
	public String detail(Model model, int accountNo) throws ClassNotFoundException, SQLException {
		Account account = as.detail(accountNo);
		
		model.addAttribute("account", account);
		
		return "account/detail";
	}
}